<hr>
<p>title: 387.first-unique-character-in-a-string<br>date: 2021-11-22 14:33:45<br>mathjax: true<br>tags:</p>
<pre><code>- LeeCode
</code></pre><p>categories: </p>
<pre><code>- LeeCode
</code></pre><p>hidden: true</p>
<h2 id="cateHidden-false"><a href="#cateHidden-false" class="headerlink" title="cateHidden: false"></a>cateHidden: false</h2><h3 id="描述"><a href="#描述" class="headerlink" title="描述"></a>描述</h3><blockquote>
<p>Given a string s, find the first non-repeating character in it and return its index. If it does not exist, return -1.</p>
</blockquote>
<h3 id="测试用例"><a href="#测试用例" class="headerlink" title="测试用例"></a>测试用例</h3><pre><code class="lang-bash">Input: s = &quot;leetcode&quot;
Output: 0

Input: s = &quot;loveleetcode&quot;
Output: 2

Input: s = &quot;aabb&quot;
Output: -1
</code></pre>
<h3 id="题解"><a href="#题解" class="headerlink" title="题解"></a>题解</h3><p>依旧是首先收集目标字符串的元素，再根据字符数去匹配目标字符串内字符数为1的字符位置。</p>
<pre><code class="lang-js">var firstUniqChar = function(s) {
    let obj = {}, result = -1; // 用于收集字符

    for(let c of s) {
        obj[c] = obj[c] ? obj[c] + 1 : 1;
    }
    // 确定位置
    for(let i in s) {
        if(obj[s[i]] === 1) {
            result = i;
            break;
        }
    }
    return result;
};
</code></pre>
<h3 id="结果"><a href="#结果" class="headerlink" title="结果"></a>结果</h3><blockquote>
<p>Accepted</p>
<p>104/104 cases passed (351 ms)</p>
<p>Your runtime beats 5.3 % of javascript submissions</p>
<p>Your memory usage beats 5.02 % of javascript submissions (61.8 MB)</p>
</blockquote>
